!<template>
  <div>
    <el-button type="primary" @click="add">添加飞机</el-button>
    <el-form inline>
      <el-form-item label="根据飞机注册号搜索">
        <el-input v-model="search" placeholder="请输入飞机号"></el-input>
      </el-form-item>
    </el-form>
    <el-table :data="tableData">
      <el-table-column label="飞机号" prop="airplane"></el-table-column>
      <el-table-column label="飞机型号" prop="model"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="edit(scope.row)" type="text" size="small"
            >编辑</el-button
          >
          <el-button type="text" @click="deleteHandler(scope.row)" size="small"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
    ></el-pagination>
    <el-dialog title="添加飞机" :visible.sync="dialogFormVisible">
      <el-form :model="formInline" inline :rules="inlineRules" ref="formInline">
        <el-form-item label="飞机注册号" prop="airplane">
          <el-input
            v-model="formInline.airplane"
            placeholder="请输入飞机注册号"
          ></el-input>
        </el-form-item>
        <el-form-item label="飞机型号" prop="model">
          <el-input
            v-model="formInline.model"
            placeholder="请输入飞机型号"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="reset('formInline')">重 置</el-button>
      <el-button type="primary" @click="confirm('formInline')">确 定</el-button>
    </el-dialog>
  </div>
</template>
  
  <script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import airplane from "@/api/airplane";
export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},

  data() {
    const validate = (rule, value, callback) => {
      if (!value) {
        callback(new Error("飞机注册号不得为空！"));
      } else {
        if (!this.validateInput(value)) {
          callback(new Error("飞机注册号不合法！"));
        } else {
          callback();
        }
      }
    };
    //这里存放数据
    return {
      tableData: [],
      formInline: {
        airplane: "",
        model: "",
        id: "",
      },
      currentPage: 1,
      pageSize: 10,
      total: 0,
      search: "",
      dialogFormVisible: false,
      inlineRules: {
        airplane: [{ required: true, validator: validate, trigger: "blur" }],
        model: [{ required: true, message: "请输入飞机型号", trigger: "blur" }],
      },
      editFlag: false, //当进行编辑时，该标记为true，当进行添加时，该标记为false
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {
    search(newVal, oldVal) {
      this.getTotal();
      this.list(1);
    },
  },
  //方法集合
  methods: {
    validateInput(input) {
      // 正则表达式，用于匹配只包含阿拉伯数字、大写英文字母和一个-号的字符串
      var regex = /^[A-Z0-9]+-[A-Z0-9]+$/;

      // 检查是否符合正则表达式规则
      if (!regex.test(input)) {
        return false;
      }

      // 检查-号是否只出现一次
      var dashCount = (input.match(/-/g) || []).length;
      if (dashCount !== 1) {
        return false;
      }

      // 检查-号是否出现在末尾或开头
      if (input.charAt(0) === "-" || input.charAt(input.length - 1) === "-") {
        return false;
      }

      // 校验通过
      return true;
    },
    deleteHandler(data) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          airplane.delete(data.id).then((res) => {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.refreshList(this.currentPage);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    add() {
      this.formInline = {
        airplane: "",
        model: "",
        id: "",
      };
      this.editFlag = false;
      this.dialogFormVisible = true;
    },
    edit: async function (data) {
      this.formInline.airplane = data.airplane;
      this.formInline.model = data.model;
      this.formInline.id = data.id;
      this.dialogFormVisible = true;
      this.editFlag = true;
    },
    reset(formInline) {
      this.$refs[formInline].resetFields();
    },
    confirm(formInline) {
      this.$refs[formInline].validate((valid) => {
        if (valid) {
          if (!this.editFlag) {
            //进行添加操作
            airplane.add(this.formInline).then((res) => {
              this.$message({
                message: "添加成功",
                type: "success",
              });
              this.dialogFormVisible = false;
              this.refreshList(this.currentPage);
              this.formInline = {
                airplane: "",
                model: "",
                id: "",
              };
            });
          } else {
            const data = {
              id: this.formInline.id,
              airplane: this.formInline.airplane,
              model: this.formInline.model,
            };
            //进行更新操作
            airplane.update(data).then((res) => {
              this.$message({
                message: "更新成功",
                type: "success",
              });
              this.dialogFormVisible = false;
              this.refreshList(this.currentPage);
              this.formInline = {
                airplane: "",
                model: "",
                id: "",
              };
            });
          }
        } else {
          console.log("error submit!!");
        }
      });
    },
    handleCurrentChange: async function (currentPage) {
      this.list(currentPage);
    },
    list: async function (currentPage) {
      const res = await airplane.list(currentPage, this.pageSize, this.search);
      this.tableData = res.data;
      this.currentPage = currentPage;
    },
    getTotal: async function () {
      const res = await airplane.total(this.search);
      this.total = res.data;
    },
    refreshList: async function (currentPage) {
      await this.getTotal();
      this.list(currentPage);
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.refreshList(1);
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
  <style scoped>
</style>